package javaweb.oa;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import oa.Utils.DBUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 模板类
@WebServlet({"/dept/list","/dept/save","/dept/detail","/dept/delete","/dept/add","/dept/edit"})
public class DeptServlet extends HttpServlet {
    //模板方法
    // 重写service方法（并没有重写doGet或者doPost方法）

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取servlet path
        String servletPath = request.getServletPath();

        if("/dept/list".equals(servletPath)){
            doList(request,response);
        }else if("/dept/save".equals(servletPath)){
            doSave(request,response);
        }else if("/dept/detail".equals(servletPath)){
            doDetail(request,response);
        }else if("/dept/delete".equals(servletPath)){
            doDelete(request,response);
        }else if("/dept/add".equals(servletPath)){
            doAdd(request,response);
        }else if("/dept/edit".equals(servletPath)){
            doEdit(request,response);
        }
    }

    protected void doList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //获取应用的根路径
        String contextPath = request.getContextPath();

        out.print("        <!doctype html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门列表页面</title>");
        out.print("		<style type='text/css'>");
        out.print("                table{");
        out.print("            height:200px;");
        out.print("            width:350px;");
        out.print("            border:2px solid pink;");
        out.print("            border-collapse:collapse;");
        out.print("        }");
        out.print("        a{");
        out.print("            color:black;");
        out.print("            text-decoration:none;");
        out.print("        }");
        out.print("        a:hover{");
        out.print("            color:pink;");
        out.print("            text-decoration:underline;");
        out.print("            cursor:pointer;");
        out.print("        }");
        out.print("		</style>");

        out.print("<script type='text/javascript'>");
        out.print("             function del(deptno){");
        out.print("         if(window.confirm('亲，删除了恢复不了哦！')){");
        out.print("             alert('正在删除，请稍后~');");

        out.print("             document.location.href = '"+contextPath+"/dept/delete?deptno='+deptno;");
        out.print("         }");
        out.print("     }");
        out.print("	</script>");

        out.print("		");
        out.print("	</head>");
        out.print("");
        out.print("	<body>");
        out.print("		<h1 align='center'>部门列表</h1>");
        out.print("		<hr color='green'/>");
        out.print("			<table border='1px' align = 'center'>");
        out.print("				<tr>");
        out.print("					<th>序号</th>");
        out.print("					<th>部门编号</th>");
        out.print("					<th>部门名称</th>");
        out.print("					<th colspan='3'>操作</th>");
        out.print("				</tr>");


        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet re = null;
        try{
            conn = DBUtil.getConnection();

            String sql = "select deptno,dname,loc from dept";
            ps = conn.prepareStatement(sql);
            re = ps.executeQuery();

            int seqNum = 1;

            while(re.next()){
                String deptno = re.getString("deptno");
                String dname = re.getString("dname");
                String loc = re.getString("loc");

                out.print("<tr>");
                out.print("	<td align='center'>"+(seqNum++)+"</td>");
                out.print("	<td align='center'>"+(deptno)+"</td>");
                out.print("	<td align='center'>"+(dname)+"</td>");
                out.print("	<td align='center'><a href='javascript:void(0)' onclick='del("+deptno+")'>删除</a></td>");
                out.print("	<td align='center'><a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a></td>");
                out.print("	<td align='center'><a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>详情</a></td>");
                out.print("</tr>");

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,re);
        }
        out.print("       </table>");
        out.print("			<hr color='pink'/>");
        out.print("			<a href='/oa/add.html'>新增部门</a>");
        out.print("	</body>");
        out.print("</html>");

    }
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");

        String deptno = request.getParameter("deptno");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        int count = 0;
        try{
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            String sql = "delete from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);
            count = ps.executeUpdate();

            //事务提交
            conn.commit();

        }catch (Exception e){
            if(conn!=null){
                try{
                    conn.rollback();
                }catch(SQLException e1){
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }

        if(count!=0){
            //DeptListServlet list = new DeptListServlet();
            //list.doGet(request,response);
            //转发
            //request.getRequestDispatcher("/dept/list").forward(request,response);

            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else{
            //request.getRequestDispatcher("/error.html").forward(request,response);

            response.sendRedirect(request.getContextPath() + "/error.html");
        }
    }

    protected void doAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");

        int count = 0;

        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = DBUtil.getConnection();
            String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);
            ps.setString(2,dname);
            ps.setString(3,loc);

            count = ps.executeUpdate();

        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }
        if(count!=0){
            //request.getRequestDispatcher("/dept/list").forward(request,response);

            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else{
            //request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/error.html");
        }
    }

    protected void doDetail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String deptno = request.getParameter("deptno");

        out.print("        <!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='UTF-8'>");
        out.print("		<title>部门详情</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1>部门详情</h1>");
        out.print("		<hr>");
        out.print("                部门编号:"+deptno+" <br>");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = DBUtil.getConnection();
            String sql = "select deptno, dname, loc from dept where deptno="+deptno+"";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");

                out.print("部门名称:"+dname+" <br>");
                out.print("部门地址:"+loc+" <br>");
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }
        out.print("        <input type='button' value='后退' onclick='window.history.back()'/>");
        out.print("	</body>");
        out.print("</html>");
    }

    protected void doSave(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");

        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;

        try{
            conn = DBUtil.getConnection();
            String sql = "update dept set dname=?,loc=? where deptno=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,dname);
            ps.setString(2,loc);
            ps.setString(3,deptno);
            count = ps.executeUpdate();

        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }

        if(count!=0){
            //request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else{
            //request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath() + "error.html");
        }
    }

    public void doEdit(HttpServletRequest request,HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("UTF-8");

        String deptno = request.getParameter("deptno");
        String contextPath = request.getContextPath();

        out.print("       <!doctype html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='UTF-8'/>");
        out.print("		<title>修改页面</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1 align='center'>修改部门</h1>");
        out.print("		<hr>");
        out.print("		<form action='"+contextPath+"/dept/save' method='post'>");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            conn = DBUtil.getConnection();
            String sql = "select deptno,dname,loc from dept where deptno=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);
            rs = ps.executeQuery();
            while(rs.next()){
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                out.print("  部门编号<input type='text' name='deptno' value="+deptno+" readonly><br>");
                out.print("          部门名称<input type='text' name='dname' value="+dname+"><br>");
                out.print("          部门地址<input type='text' name='loc' value="+loc+"><br><br>");
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }
        out.print("        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        out.print("			<input type='submit' value='保存' />");
        out.print("		</form>");
        out.print("	</body>");
        out.print("</html>");
    }

}
